﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DSheet.Core.CommonData;
using DSheet.Core;

namespace DExcelServiceApp
{
    public partial class BDomainList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (DBContext context = new DBContext())
                {
                    List<BDomain> domains = new CommonDataService().GetDomains(context);

                    _ctlListDomain.DataSource = domains;
                    _ctlListDomain.DataBind();
                }
            }
        }

        protected void _ctlBtnCreate_Click(object sender, EventArgs e)
        {
            using (DBContext context = new DBContext())
            {
                BDomain newDomain = new BDomain();
                newDomain.Id = Guid.NewGuid();
                newDomain.Name = _ctlEditName.Text;
                if (!string.IsNullOrEmpty(_ctlHiddenParentId.Value))
                {
                    newDomain.ParentId = new Guid(_ctlHiddenParentId.Value);
                }
                new CommonDataService().SaveDomain(context, newDomain);

                List<BDomain> domains = new CommonDataService().GetDomains(context);

                _ctlListDomain.DataSource = domains;
                _ctlListDomain.DataBind();

                new CommonDataService().SyncBDomainToDim(context);
            }
        }

        protected void _ctlBtnSync_Click(object sender, EventArgs e)
        {
            using (DBContext context = new DBContext())
            {
                new CommonDataService().SyncBDomainToDim(context);
            }
        }

        protected void _ctlListDomain_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Guid domainId = new Guid(e.CommandArgument.ToString());

            using (DBContext context = new DBContext())
            {
                BDomain domain = new CommonDataService().GetDomain(context, domainId);
                _ctlHiddenParentId.Value = domain.Id.ToString();
                _ctlEditParent.Text = domain.Name;
            }
        }
    }
}